//
//  Spade.m
//  PVB
//
//  Created by huang kun on 5/31/10.
//  Copyright 2010 UESTC. All rights reserved.
//

#import "Spade.h"


@implementation Spade

@synthesize delegate;

- (void) dealloc {
	NSLog(@"deallocing %@",self);
	delegate = nil;
	[self removeAllChildrenWithCleanup:YES];
	[super dealloc];
}

- (id) init{
	if( (self = [super init]) ){
	//	bg = [CCSprite spriteWithFile:@"Spade_bg.png"];
	//	[self addChild:bg z:1];
	//	bg.position = CGPointZero;
		
		spade = [CCSprite spriteWithFile:@"spade.png"];
		[self addChild:spade];
		spade.position = CGPointZero;
		delegate = nil;
	}
	return self;
}

- (void) onEnter{
	[super onEnter];
	[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
}

- (void) onExit{
	[[CCTouchDispatcher sharedDispatcher] removeDelegate:self];
	[super onExit];
}

- (BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event{
	CGPoint p = [touch locationInView:[touch view]];
	p = [[CCDirector sharedDirector] convertToGL:p];
	
	CGRect rect = CGRectMake(-0.5 * spade.contentSize.width, -0.5 * spade.contentSize.height,
							 spade.contentSize.width, spade.contentSize.height);
	rect =  CGRectApplyAffineTransform(rect, [self nodeToParentTransform]);
	if(delegate && CGRectContainsPoint(rect, p)){
		[spade stopAllActions];
		return YES;
	}
	else {
		return NO;
	}
}

- (void) ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event{
	CGPoint p = [touch locationInView:[touch view]];
	p = [[CCDirector sharedDirector] convertToGL:p];
	
	spade.position = ccpSub(p, self.position);
}

- (void) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event{
	CGPoint p = [touch locationInView:[touch view]];
	p = [[CCDirector sharedDirector] convertToGL:p];
	CGPoint digPosition = [delegate convertToGridPosition:p];
	
	if(!CGPointEqualToPoint(digPosition, CGPointZero)){
		[delegate removePlantByPosition:p];
		//铲子中心在植物种植点右上方
		digPosition = ccpSub(digPosition, self.position);
		//digPosition = ccpAdd(digPosition,ccp(0.5*spade.contentSize.width,0.5*spade.contentSize.height));
		
		
		spade.position = ccpSub(p, self.position);
		id move = [CCMoveTo actionWithDuration:0.2 position:digPosition];
		id rotation = [CCRotateBy actionWithDuration:0.15 angle:20];
		id moveLeft = [CCMoveBy actionWithDuration:0.15 position:ccp(-10,-15)];
		id spawn = [CCSpawn actions:rotation,moveLeft,nil];
		id moveHome = [CCMoveTo actionWithDuration:ccpDistance(self.position, CGPointZero)/800 position:CGPointZero];
		id dig = [CCSequence actions:spawn,[spawn reverse],nil];
		
		[spade stopAllActions];
		[spade runAction:[CCSequence actions:move,[CCRepeat actionWithAction:dig times:2],moveHome,nil]];
	}
	else {
		id moveHome = [CCMoveTo actionWithDuration:ccpDistance(self.position, CGPointZero)/800 position:CGPointZero];
		[spade runAction:moveHome];

	}
}

@end
